package edu.yuhf.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.stereotype.Repository;

import edu.yuhf.dao.iface.ImageDao;
import edu.yuhf.entity.Image;

@Repository("imageDao")
public class ImageOracleJdbcDaoImpl implements ImageDao {
	private static final Logger log = Logger.getLogger(ImageOracleJdbcDaoImpl.class);

	@Resource
	JdbcTemplate jdbcTemplate;
	@Resource
	private DataFieldMaxValueIncrementer imageSequence;

	@Override
	public Image getImage(int id) {
		String sql = "select * from image where id=?";
		Image image = jdbcTemplate.queryForObject(sql, new Object[] { id },
				(RowMapper<Image>) (rs, index) -> new Image(rs.getInt(1), rs.getBlob(2)));
		return image;
	}

	@Override
	public int insertImage(File file) {
		String insertSql = "insert into image values(?,?)";
		final LobHandler lobHandler = new DefaultLobHandler();
		InputStream is;
		int count = 0;
		Image image=new Image();
		try {
			is = new FileInputStream(file);
			count = jdbcTemplate.execute(insertSql, new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
				protected void setValues(PreparedStatement psmt, LobCreator lobCreator) throws SQLException {
					int id=imageSequence.nextIntValue();
					image.setId(id);
					psmt.setInt(1, id);
					lobCreator.setBlobAsBinaryStream(psmt, 2, is, (int) file.length());
				}
			});
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image.getId();
	}

}
